import React, { useEffect, useMemo, useRef, useState, useContext } from "react";
import { Button, Col, Form, Input, Row, Select, Space, DatePicker, Table, Radio, Dropdown, Popconfirm } from "antd";
import {
  CopyOutlined, DeleteOutlined,
  EditOutlined, FileSearchOutlined,
  PlusOutlined,
  PrinterOutlined,
  SettingTwoTone,
  UploadOutlined
} from "@ant-design/icons";
import AdvancedSearchForm from "../../components/pageContainer/AdvancedSearchForm";
import Toolbar from "../../components/pageContainer/Toolbar";
import PaginationTable from "../../components/pageContainer/PaginationTable";
import { getSaleOrderList } from "../../api/sale/saleOrdersPage";
import { observable } from "mobx";
import PageContext, { CONTEXT_VALUE } from "../../components/pageContainer/PageContext";
import { DATE_FORMAT_YYYY_MM_DD, DEFAULT_NUM_0, DEFAULT_NUM_1, DEFAULT_PAGE_NUM } from "../../utils/constant";
import OrganizationModal from "../../components/modal/OrganizationModal";

const dayjs = require("dayjs");
const { RangePicker } = DatePicker;

/**
 * 销售管理--销售订单
 * @returns {JSX.Element}
 * @constructor
 */
const SaleOrderListPage = () => {
  const [options, setOptions] = useState([]);
  const [value, setValue] = useState(1);
  const [contextValue, setContextValue] = useState(CONTEXT_VALUE);
  const companyModalRef = useRef(null);

  const [initialValues, setInitialValues] = useState({
    dateRange: [dayjs(), dayjs()]
  });

  const columns = [
    {
      title: "系统订单号",
      dataIndex: "sbillID"
    },
    {
      title: "合同号",
      dataIndex: "scusOrderCode"
    },
    {
      title: "所属公司",
      dataIndex: "dname"
    },
    {
      title: "部门",
      dataIndex: "dname"
    },
    {
      title: "业务人员",
      dataIndex: "ename"
    },
    {
      title: "销售客户",
      dataIndex: "scustmerID"
    },
    {
      title: "数量",
      dataIndex: "quantity"
    },
    {
      title: "业务单位数量",
      dataIndex: "quantityKg"
    },
    {
      title: "总金额",
      dataIndex: "sumAmount"
    },
    {
      title: "货运状态",
      dataIndex: "stranStatus"
    },
    {
      title: "交付日期",
      dataIndex: "sdate"
    },
    {
      title: "单据日期",
      dataIndex: "sdeliveryDate"
    },
    {
      title: "制单人员",
      dataIndex: "addUser"
    },
    {
      title: "审核状态",
      dataIndex: "checkName"
    },
    {
      title: "（反）审核人",
      dataIndex: "address"
    },
    {
      title: "摘要",
      dataIndex: "sexplanation"
    },
    {
      title: "操作",
      key: "operation",
      fixed: "right",
      width: 100,
      render: () => <a>新增</a>
    }
  ];

  useEffect(() => {
    getOptions().then((res) => {
      setOptions(res);
    });
  }, []);

  const getOptions = () => {
    return new Promise((resolve) => {
      const arr = [
        {
          value: "jack",
          label: "Jack"
        },
        {
          value: "lucy",
          label: "Lucy"
        },
        {
          value: "disabled",
          disabled: true,
          label: "Disabled"
        },
        {
          value: "Yiminghe",
          label: "yiminghe"
        }
      ];
      resolve(arr);
    });
  };

  const handleOpenCompanyModal = () => {
    companyModalRef.current.showModal();
  };

  const getFieldItems = () => {
    const fields = [];

    fields.push(
      <Form.Item
        name={`sbillID`}
        label={`系统订单号`}
      >
        <Input placeholder="请输入" />
      </Form.Item>
    );

    fields.push(
      <Form.Item label={`所属公司`}>
        <Space className={"operation_form_item"}>
          <Form.Item name="username" noStyle>
            <Select
              showSearch
              filterOption={(input, option) => (option?.label ?? "").includes(input)}
              options={options}
            />
          </Form.Item>
          <SettingTwoTone onClick={handleOpenCompanyModal} />
        </Space>
      </Form.Item>
    );

    fields.push(
      <Form.Item label={`业务人员`}>
        <Space className={"operation_form_item"}>
          <Form.Item name="username" noStyle>
            <Select
              showSearch
              filterOption={(input, option) => (option?.label ?? "").includes(input)}
              options={options}
            />
          </Form.Item>
          <SettingTwoTone />
        </Space>
      </Form.Item>
    );

    fields.push(
      <Form.Item
        name={`dateRange`}
        label={`单据日期`}
      >
        <RangePicker defaultPickerValue={[dayjs(), dayjs()]} />
      </Form.Item>
    );

    fields.push(
      <Form.Item name="username" label={`货运状态`}>
        <Select
          showSearch
          filterOption={(input, option) => (option?.label ?? "").includes(input)}
          options={options}
        />
      </Form.Item>
    );

    fields.push(
      <Form.Item label={`销售客户`}>
        <Space className={"operation_form_item"}>
          <Form.Item name="username" noStyle>
            <Select
              showSearch
              style={{ width: `100%` }}
              filterOption={(input, option) => (option?.label ?? "").includes(input)}
              options={options}
            />
          </Form.Item>
          <SettingTwoTone />
        </Space>
      </Form.Item>
    );

    fields.push(
      <Form.Item name="username" label={`审核状态`}>
        <Radio.Group onChange={e => setValue(e.target.value)} value={value}>
          <Radio value={1}>A</Radio>
          <Radio value={2}>B</Radio>
          <Radio value={3}>C</Radio>
          <Radio value={4}>D</Radio>
        </Radio.Group>
      </Form.Item>
    );

    return fields;
  };

  const handleSearch = () => {
    const { fieldsValue, pagination } = contextValue;
    const post = { ...fieldsValue, ...pagination };

    const { dateRange } = fieldsValue;
    if (dateRange) {
      post.dateFrom = dayjs(dateRange[0]).format(DATE_FORMAT_YYYY_MM_DD);
      post.dateTo = dayjs(dateRange[1]).format(DATE_FORMAT_YYYY_MM_DD);
    }

    getSaleOrderList(post).then(res => {
      pagination.total = res?.recordCount ?? 0;
      const dataList = res.list.map((item, index) => {
        return { index, ...item };
      });
      setContextValue({ dataSource: dataList, fieldsValue, pagination });
    });
  };

  /*-------------------------审核下拉菜单配置--start-----------------------*/
  const handleMenuClick = (e) => {
  };
  const handleButtonClick = (e) => {
  };

  const items = [
    {
      label: "审核",
      key: "1",
      icon: <FileSearchOutlined />
    },
    {
      label: "反审核",
      key: "2",
      icon: <FileSearchOutlined />
    }
  ];
  const menuProps = {
    items,
    onClick: handleMenuClick
  };
  /*-------------------------审核下拉菜单配置--end-----------------------*/

  const isSelectOnly = useMemo(() => {
    return contextValue?.selectedRowKeys?.length === 1;
  }, [contextValue]);

  const getToolbar = () => {
    return (
      <Space>
        <Button icon={<PrinterOutlined />}>打印</Button>
        <Button icon={<UploadOutlined />}>上传</Button>
        <Button type="primary" icon={<CopyOutlined />}>复制</Button>
        <Dropdown.Button menu={menuProps} onClick={handleButtonClick}>
          审核
        </Dropdown.Button>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
        <Button type="primary" icon={<EditOutlined />} disabled={!isSelectOnly}>修改</Button>
        <Button danger icon={<DeleteOutlined />}>删除</Button>
      </Space>
    );
  };

  const handleAdd = () => {
    const { selectedRowKeys } = contextValue;
    console.log(selectedRowKeys);
  };

  const EditableContext = React.createContext(null);
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  const EditableCell = ({
                          title,
                          editable,
                          children,
                          dataIndex,
                          record,
                          handleSave,
                          ...restProps
                        }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex]
      });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values
        });
      } catch (errInfo) {
        console.log("Save failed:", errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`
            }
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell
    }
  };

  const expandedRowRender = () => {
    const columns = [
      {
        title: "生产日期",
        dataIndex: "date",
        key: "date"
      },
      {
        title: "工作中心1",
        dataIndex: "name",
        key: "name",
        onCell: (record) => ({
          record,
          editable: true,
          dataIndex: "name",
          title: "工作中心1",
          handleSave
        })
      },
      {
        title: "工作中心2",
        dataIndex: "upgradeNum",
        key: "upgradeNum"
      },
      {
        title: "工作中心3",
        dataIndex: "operation",
        key: "operation"
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        render: (_, record) => (
          <Popconfirm title="确定要删除吗？" onConfirm={() => handleDelete(record.key)}>
            <a>Delete</a>
          </Popconfirm>
        )
      }
    ];
    const data = [];
    for (let i = 0; i < 3; ++i) {
      data.push({
        key: i.toString(),
        date: "2014-12-24 23:12:00",
        name: "This is production name",
        upgradeNum: "Upgraded: 56"
      });
    }

    return <Table columns={columns} dataSource={data} pagination={false} components={components} />;
  };

  const handleSave = (row) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row
    });
    // setDataSource(newData);
  };

  const handleDelete = (key) => {
    const newData = dataSource.filter((item) => item.key !== key);
  };

  return (
    <PageContext.Provider value={{ contextValue, setContextValue, handleSearch }}>
      <div className={`page_container_wrap`}>
        <AdvancedSearchForm fieldItems={getFieldItems()} initialValues={initialValues} />
        <Toolbar renderToolbar={() => getToolbar()} />
        <PaginationTable dataSource={contextValue.dataSource} title={() => `aaaaaaa`}
                         columns={columns} rowKey={`index`} expandedRowRender={expandedRowRender} />
      </div>
      <OrganizationModal ref={companyModalRef} />
    </PageContext.Provider>
  );
};

export default SaleOrderListPage;
